<?php
namespace app\system\controller;

use app\common\model\ShopGoodsModel;
use app\common\model\ShopGoodsSkuModel;
use think\Db;
use think\Request;

class ShopGoodsStockController extends BaseController
{

    private $goodsModel;
    private $goodsSkuModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->goodsModel    = new ShopGoodsModel();
        $this->goodsSkuModel = new ShopGoodsSkuModel();
    }

    /**
     * 首页
     */
    public function index()
    {
        $map       = [];
        $query     = [];
        $map['site_id'] = $this->getSiteId();
        $query['site_id'] = $this->getSiteId();
        $goodsName = $this->request->param('goods_name');
        if (!empty($goodsName)) {
            $map['goods_name']   = ['like', '%' . $goodsName . '%'];
            $query['goods_name'] = $goodsName;
        }
        $list           = $this->goodsModel->alias('t1')
            ->field('t2.sku_id,t1.album,t1.goods_id,t1.goods_name,t2.sku_name,t2.goods_stock,t1.alert_num')
            ->join('__SHOP_GOODS_SKU__ t2', 't1.goods_id=t2.goods_id')
            ->where("t2.goods_stock<=t1.alert_num")
            ->where($map)
            ->paginate(12, false, ['query' => $query]);
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }

    /**
     * 增加单个库存
     */
    public function updateStock()
    {
        $skuId       = $this->request->param('sku_id/d');
        $goods_stock = $this->request->param('goods_stock/d');
        $stockpiling = $this->request->param('stockpiling/d');
        $this->goodsSkuModel->where('sku_id', $skuId)->setField('goods_stock', ($goods_stock + $stockpiling));
        $this->success('操作成功！');
    }

    /**
     * 批量保存库存
     */
    public function batchUpdateStock()
    {
        $stock     = $this->request->param('stock/a');
        $stockList = [];
        foreach ($stock as $v) {
            if (isset($v['sku_id'])) {
                $stockList[] = ['sku_id' => $v['sku_id'], 'goods_stock' => ($v['goods_stock'] + $v['stockpiling'])];
            }
        }
        if ($stockList) {
            $this->goodsSkuModel->saveAll($stockList);
            $this->success('操作成功！');
        } else {
            $this->error('没有要操作得数据');
        }
    }

}
